package com.mettle.loyaltycard.parser;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.mettle.loyaltycard.model.LoyaltyCard;

public class InputFileParser {

	private static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
	public static Map<String, LoyaltyCard> getCards(String filePath)
			throws IOException, ParseException {
		Map<String, LoyaltyCard> loyaltyCards = new HashMap<String, LoyaltyCard>();
		File file = new File(filePath);
		FileInputStream fis = new FileInputStream(file);
		DataInputStream in = new DataInputStream(fis);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		while ((strLine = br.readLine()) != null) {
			parseLine(strLine, loyaltyCards);
		}
		in.close();
		return loyaltyCards;
	}

	static void parseLine(String strLine,
			Map<String, LoyaltyCard> loyaltyCards) throws ParseException {
		strLine.replaceAll(" ", "");
		String[] parsedValues = strLine.split(",");
		String cardNo = parsedValues[2];
		if ("".equals(cardNo)) {
			return;
		}
		LoyaltyCard loyaltyCard = null;
		LoyaltyCard existingLoyaltyCard = loyaltyCards.get(cardNo);
		if (existingLoyaltyCard == null) {
			loyaltyCard = new LoyaltyCard(Integer.parseInt(cardNo));
			loyaltyCards.put(cardNo, loyaltyCard);
		} else {
			loyaltyCard = existingLoyaltyCard;
		}
		loyaltyCard.updateCustomer(parsedValues[0], parsedValues[1]);
		loyaltyCard.addTransaction(Double.valueOf(parsedValues[3]), getDate(parsedValues[4]), Long.valueOf(parsedValues[5]));
	}

	static Date getDate(String string) {
		try {
			return dateFormat.parse(string);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
}
